package com.iscreen.core.trading.beans;

import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.jboss.ejb3.annotation.RemoteBinding;

import com.iscreen.core.services.flow.FlowService;
import com.iscreen.core.services.flow.FlowType;
import com.iscreen.core.services.parameters.ParameterConstants;
import com.iscreen.core.services.parameters.ParametersHandler;
import com.iscreen.utils.dates.DateUnit;
import com.iscreen.utils.dates.DateUtils;
import com.iscreen.utils.exceptions.IScreenException;

/**
 * Session Bean implementation class TradingResultsHandlerBean
 */
@Stateless
@RemoteBinding(jndiBinding="TradingDataImporter")
public class TradingDataImporterBean implements TradingDataImporter {

	@EJB
	private ParametersHandler parametersHandler;

    /**
     * Default constructor. 
     */
    public TradingDataImporterBean() {
        // TODO Auto-generated constructor stub
    }

	private Date getLastImportDate() throws IScreenException
	{
		String lastImportDate = parametersHandler.getParameterValue(ParameterConstants.SECTION_DATA_IMPORT, ParameterConstants.PARAM_DAILY_DATA_LAST_IMPORT_DATE, ParameterConstants.DEFAULT_DAILY_DATA_LAST_IMPORT_DATE);		
		return DateUtils.parseDate(lastImportDate);
	}

	private void importData(Date lastImportDate) throws IScreenException
	{
		Date today = new Date();
		lastImportDate = DateUtils.add(today, DateUnit.DAY, -2);
		for (Date date = lastImportDate; date.before(today); date = DateUtils.add(date, DateUnit.DAY))
		{
			importDailyData(date);
			updateLastImportDate(date);
		}
	}

	private void importDailyData(Date date) throws IScreenException
	{
		FlowService.getInstance().startFlow(FlowType.IMPORT_DAILY_DATA, date);
	}

	private void updateLastImportDate(Date date) throws IScreenException
	{
		String importDateStr = DateUtils.formatDate(date);
		parametersHandler.updateParameterValue(ParameterConstants.SECTION_DATA_IMPORT, ParameterConstants.PARAM_DAILY_DATA_LAST_IMPORT_DATE, importDateStr);
	}
	
	@Override
	public void importDailyResults() throws IScreenException
	{
		Date lastImportDate = getLastImportDate();
		importData(lastImportDate);
	}


}
